package com.cty.sortAlgorithms;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/*
*
*堆排序
*
* */
public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {-999,3,8,5};
        heapSort(arr);
        System.out.println("结果:" + Arrays.toString(arr));
        //测试一下堆排序
        //用80000个数据来测试一下
        int [] arr2 = new int[8000000];
        for (int i = 0;i < 8000000;i++) {
            arr2[i] = (int)(Math.random() * 8000000) ;
        }
        //实际计算一下冒泡算法所需要的时间
        Date date1 = new Date();
        //格式化一下时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format1 = simpleDateFormat.format(date1);
        System.out.println(format1);
        heapSort(arr2);
        Date date2 = new Date();
        String format2 = simpleDateFormat.format(date2);
        System.out.println(format2);//八百万个数据在2秒左右
    }
    public static void heapSort(int[] arr) {
        int temp = 0;
        for (int i = arr.length / 2 - 1;i >= 0;i--) {
            adjustHeap(arr,i,arr.length);
        }
        for (int j = arr.length - 1; j > 0;j--) {
            temp = arr[j];
            arr[j] = arr[0];
            arr[0] = temp;
            adjustHeap(arr,0,j);
        }
    }
    public static void adjustHeap(int[] arr,int i, int length) {
        int temp = arr[i];
        for (int k = i * 2 + 1; k < length;k = k * 2 + 1) {
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k++;
            }
            if (arr[k] > temp) {
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }
        arr[i] = temp;
    }
}
